package com.xsq.page;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.xsq.BaseApplication;
import com.xsq.Constants;
import com.xsq.R;
import com.xsq.utils.HttpUtil;
import com.xsq.utils.RestartAPPTool;
import com.xsq.utils.StatusUtils;
import com.xsq.view.easykeyboard.SystemKeyboard;
import com.xsq.view.easykeyboard.action.KeyBoardActionListener;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;

@ContentView(R.layout.fragment_main_paramsset)
public class MainParamSet extends BaseFragment implements View.OnClickListener {

    private View rootView;
    @ViewInject(R.id.keyboard)
    SystemKeyboard keyboard;
    @ViewInject(R.id.edit_win_no)
    EditText editWinNo;
    @ViewInject(R.id.edit_ip)
    EditText editIp;
    @ViewInject(R.id.edit_port)
    EditText editPort;
    @ViewInject(R.id.radioAuto)
    RadioButton radioAuto;
    @ViewInject(R.id.radioInput)
    RadioButton radioInput;
    @ViewInject(R.id.auto_price)
    EditText editAutoPrice;
    @ViewInject(R.id.auto_price_text)
    TextView editAutoPriceText;
    @ViewInject(R.id.submit_btn)
    Button submitBtn;

    public static MainParamSet newInstance() {
        MainParamSet f = new MainParamSet();
        Bundle args = new Bundle();
        //args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null) {
            rootView = x.view().inject(this, inflater, container);
        }
        initData();
        initListener();
        editWinNo.requestFocus();
        submitBtn.setOnClickListener(this);
        return rootView;
    }

    //***初始化数据回填到输入框***//
    private void initData() {
        if(BaseApplication.getInstance().hasConfiged()) {
            if(!TextUtils.isEmpty(BaseApplication.getInstance().getWinId())) {
                editWinNo.setText(BaseApplication.getInstance().getWinId());
            }
            if(!TextUtils.isEmpty(BaseApplication.getInstance().getBaseUrl()) && BaseApplication.getInstance().getBaseUrl().contains(":")) {
                String[] url = BaseApplication.getInstance().getBaseUrl().split(":");
                //[http]:[//119.45.221.111]:[8090]
                editIp.setText(url[1].substring(2));
                editPort.setText(url[2]);
            }
            int priceType = BaseApplication.getInstance().getPriceType();
            if(priceType == PriceType.Input) {
                radioInput.setChecked(true);
                editAutoPrice.setVisibility(View.GONE);
                editAutoPriceText.setVisibility(View.VISIBLE);
            }else {
                radioAuto.setChecked(true);
                editAutoPrice.setVisibility(View.VISIBLE);
                editAutoPrice.setText(BaseApplication.getInstance().getAutoPrice());
                editAutoPriceText.setVisibility(View.GONE);
            }
        }
    }

    //***初始化输入框和自定义键盘的联系***//
    private void initListener() {
        editWinNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    keyboard.setEditText(editWinNo);
                }
            }
        });
        editIp.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    keyboard.setEditText(editIp);
                }
            }
        });
        editPort.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    keyboard.setEditText(editPort);
                }
            }
        });
        editAutoPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    keyboard.setEditText(editAutoPrice);
                }
            }
        });
        radioAuto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    editAutoPrice.setVisibility(View.VISIBLE);
                    editAutoPriceText.setVisibility(View.GONE);
                }
            }
        });
        radioInput.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    editAutoPrice.setVisibility(View.GONE);
                    editAutoPriceText.setVisibility(View.VISIBLE);
                }
            }
        });
        keyboard.setOnKeyboardActionListener(new KeyBoardActionListener() {
            @Override
            public void onComplete() {

            }

            @Override
            public void onTextChange(Editable editable) {

            }

            @Override
            public void onClear() {

            }

            @Override
            public void onClearAll() {

            }
        });
    }

    private void sync(String ip, String port, final String winId, final int type, final String autoPrice) {
        final String baseUrl = "http://" + ip + ":" + port;
        HashMap<String, String> params = new HashMap<>();
        //params.put("posSn", Utils.getAndroidId(getActivity()));
        params.put("posSn", winId);
        params.put("posIp", /*NetWorkUtils.getIPAddress(getActivity())*/ip);
        params.put("posPort", port);
        params.put("merchantNo", winId);
        params.put("windowNo", winId);
        HttpUtil.getInstance().get(baseUrl + Constants.url_bindPos, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                LogUtil.e("response==" + response.toString());
                Toast.makeText(getActivity(), response.optString("msg"), Toast.LENGTH_SHORT).show();
                if(response.optInt("ret") == 0) {
                    BaseApplication.getInstance().setConfig(baseUrl, winId, type, autoPrice);
                    showDialog("设置成功，正在重启，请稍候", 2000, new DialogCloseListener() {
                        @Override
                        public void onClose() {
                            RestartAPPTool.restartAPP(getContext());
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                StatusUtils.handleError(ex, getActivity());
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit_btn:
                /*Intent intent = new Intent(this, NFCControllerActivity.class);
                startActivity(intent);*/
                String ip = editIp.getText().toString();
                String port = editPort.getText().toString();
                //String merId = editMerId.getText().toString();
                String winId = editWinNo.getText().toString();
                if(TextUtils.isEmpty(ip)) {
                    Toast.makeText(getActivity(), "请输入IP", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(port)) {
                    Toast.makeText(getActivity(), "请输入Port", Toast.LENGTH_SHORT).show();
                    return;
                }
                /*if(TextUtils.isEmpty(merId)) {
                    Toast.makeText(getActivity(), "请输入商户号", Toast.LENGTH_SHORT).show();
                    return;
                }*/
                if(TextUtils.isEmpty(winId)) {
                    Toast.makeText(getActivity(), "请输入窗口号", Toast.LENGTH_SHORT).show();
                    return;
                }
                int priceType = 0;
                String autoPrice = null;
                if(radioInput.isChecked()) {
                    priceType = 1;//输入扣款
                    autoPrice = "0";
                }else {
                    priceType = 2;//自动扣款
                    autoPrice = editAutoPrice.getText().toString();
                    if(TextUtils.isEmpty(autoPrice)) {
                        Toast.makeText(getActivity(), "请输入自动扣款金额", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    double autoPriceD = Double.valueOf(autoPrice);
                    if(autoPriceD < 0) {
                        Toast.makeText(getActivity(), "自动扣款的金额需要大于0", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                sync(ip, port, winId, priceType, autoPrice);
                break;
        }
    }
}
